import grace from "../../../utils/grace.js";
import {Product} from 'product-model.js';
import {Cart} from '../shopcart/cart-model.js';
import {Favorite} from "../favorite/favorite-model";

const app = getApp()
let product = new Product();
let cart = new Cart();
let favorite = new Favorite();
let WxParse = require('../../../utils/wxParse/wxParse.js');

grace.page({
    /**
     * 页面的初始数据
     */
    data: {
        cangotop: false,// 回到顶部
        switch_position: 'relative',// 开关位置
        ellipsis: true, // 文字是否收起，默认收起
        switch: ['content'],
        switchStrs: ['详情'],
        currentIndex: 0,
        currentItem: 'content',
        num: 1,//初始数量
        minusStatus: 'disabled', // 使用data数据对象设置样式名
        plusStatus: 'disabled',
        choose_modal: "none", // 规格数量框
        flag: 0,//点选规格时来源 0：规格点 1：立即购买 2：加入购物车
        goods: {},//商品信息
        amount: 0,// 合计价格
        stock_count: 0,// 商品库存
        is_collect: false// 是否收藏
    },
    onLoad(e) {
        let params = {
            'product_id': e.product_id
        }
        if(wx.getStorageSync('partner_id')){
            params['partner_id'] = wx.getStorageSync('partner_id')
        }
        product.getProductDetail(params, (data) => {
            this.$data.goods = data;
            this.$data.amount = data.lst_price;
            this.$data.stock_count = data.qty_available;
            WxParse.wxParse('content', 'html', this.$data.goods.description_app, this, 5);
        })

        if (wx.getStorageSync('token')) {
            favorite.getFavoriteProductData({
                'token': wx.getStorageSync('token'),
                'partner_id': wx.getStorageSync('partner_id'),
                'product_id': e.product_id
            }, (data) => {
                if (data == 'yes') {
                    this.$data.is_collect = true;
                } else {
                    this.$data.is_collect = false;
                }
            })
        }
    },
    ellipsis() {
        let value = !this.data.ellipsis;
        this.setData({
            ellipsis: value
        })
    },
    switchTap(e) {
        this.setData({
            currentIndex: e.currentTarget.dataset.index,
            currentItem: this.data.switchStrs[e.currentTarget.dataset.index]
        })
    },
    changeNum(num) {
        // 只有大于一件的时候，才能normal状态，否则disable状态
        let minusStatus = num <= 1 ? 'disabled' : 'normal';
        let plusStatus = num >= this.$data.stock_count ? 'disabled' : 'normal';
        // 将数值与状态写回
        this.$data = {
            num: num,
            minusStatus: minusStatus,
            plusStatus: plusStatus
        };
        this.change_price();
    },
    /* 点击减号 */
    bindMinus() {
        let num = this.data.num;
        // 如果大于1时，才可以减
        if (num > 1) {
            num--;
        }
        this.changeNum(num);
    },
    bindPlus() {
        let num = this.data.num;
        // 如果小于库存时，才可以加
        if (num < this.$data.stock_count) {
            num++;
        }
        this.changeNum(num);
    },
    /* 输入框事件 */
    bindManual(e) {
        let num = e.detail.value;
        if (isNaN(num)) {
            num = 1;
        }
        if (num > this.$data.stock_count) {
            num = this.$data.stock_count;
        }
        this.changeNum(num);
    },
    /*弹出*/
    modal_show(e) {
        let flag = e.currentTarget.dataset.flag;
        this.setData({
            flag: flag,
            choose_modal: "block",
        });
    },
    /*隐藏*/
    modal_none() {
        this.setData({
            choose_modal: "none",
        });
    },
    change_price() {
        this.$data.amount = this.$data.goods.lst_price * this.$data.num;
    },
    // 添加购物车
    addCart(e) {
        if (this.$data.choose_modal == 'none') {
            let flag = e.currentTarget.dataset.flag;
            this.setData({
                flag: flag,
                choose_modal: "block",
            });
        } else {
            let token = wx.getStorageSync('token');
            // token校验
            if (!token) {
                wx.removeStorageSync('userInfo');
                wx.navigateTo({
                    url: '/pages/common/authorize/index'
                })
            }

            cart.addCartData({
                'token': wx.getStorageSync('token'),
                'partner_id': wx.getStorageSync('partner_id'),
                'product_id': this.$data.goods.id,
                'product_uom_qty': this.$data.num
            }, (data) => {
                this.modal_none();
                if (data.code == 0) {
                    wx.showToast({
                        title: '添加成功',
                        icon: 'success',
                        duration: 2000,
                        mask: true
                    })
                } else {
                    wx.showToast({
                        title: '添加失败',
                        icon: 'fail',
                        duration: 2000,
                        mask: true
                    })
                }
            })
        }
    },
    // 立即购买
    buyNow(e) {
        let token = wx.getStorageSync('token');
        // token校验
        if (!token) {
            wx.removeStorageSync('userInfo');
            wx.navigateTo({
                url: '/pages/common/authorize/index'
            })
        }

        let params = {
            'token': wx.getStorageSync('token'),
            'partner_id': wx.getStorageSync('partner_id'),
            'product_id': this.$data.goods.id,
            'product_uom_qty': this.$data.num
        }
        cart.addCartData(params, (data) => {
            this.modal_none();
            if (data.code == 0) {
                wx.switchTab({
                    url: '/pages/mall/shopcart/index'
                })
            } else {
                wx.showToast({
                    title: '购买失败',
                    icon: 'fail',
                    duration: 2000,
                    mask: true
                })
            }
        })
    },
    // 确认
    buy() {
        let token = wx.getStorageSync('token');
        // token校验
        if (!token) {
            wx.removeStorageSync('userInfo');
            wx.navigateTo({
                url: '/pages/common/authorize/index'
            })
        }

        let that = this;
        let params = {
            'token': wx.getStorageSync('token'),
            'partner_id': wx.getStorageSync('partner_id'),
            'product_id': this.$data.goods.id,
            'product_uom_qty': this.$data.num
        }
        cart.addCartData(params, (data) => {
            this.modal_none();
            if (data.code == 0) {
                console.log('跳转：flag=' + that.$data.flag);
                if (that.$data.flag == 1) {
                    wx.switchTab({
                        url: '/pages/mall/shopcart/index'
                    })
                    console.log('跳转完成');
                } else {
                    wx.showToast({
                        title: '添加成功',
                        icon: 'success',
                        duration: 2000,
                        mask: true
                    })
                }
            } else {
                wx.showToast({
                    title: '添加失败',
                    icon: 'fail',
                    duration: 2000,
                    mask: true
                })
            }
        })
    },
    // 获取滚动条当前位置
    onPageScroll(e) {
        if (e.scrollTop > 100) {//页面距离大于100px,则显示回到顶部控件
            this.setData({
                cangotop: true
            });
        } else {
            this.setData({
                cangotop: false
            });
        }

        if (e.scrollTop > 600) {//页面距离大于100px,则显示回到顶部控件
            this.setData({
                switch_position: 'fixed'
            });
        } else {
            this.setData({
                switch_position: 'relative'
            });
        }
    },
    //回到顶部，内部调用系统API
    goTop(e) {  // 一键回到顶部
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，暂无法使用该功能，请升级后重试。'
            })
        }
    },
    // 转发、分享
    onShareAppMessage(res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target)
        }
        return {
            title: this.$data.goods.name,
            success: function (res) {
                // 转发成功
                console.log(res)
            },
            fail: function (res) {
                // 转发失败
            }
        }
    },
    collect() {
        let token = wx.getStorageSync('token');
        // token校验
        if (!token) {
            wx.removeStorageSync('userInfo');
            wx.navigateTo({
                url: '/pages/common/authorize/index'
            })
        }

        let that = this;
        if (this.$data.is_collect) {
            wx.showToast({
                title: '取消成功',
                icon: 'loading',
            })
            that.$data.is_collect = false;
            favorite.deleteFavoriteData({
                'token': wx.getStorageSync('token'),
                'partner_id': wx.getStorageSync('partner_id'),
                'product_id': that.$data.goods.id
            }, (data) => {
            })
        } else {
            wx.showToast({
                title: '收藏成功',
                icon: 'loading',
            })
            that.$data.is_collect = true;
            favorite.addFavoriteData({
                'token': wx.getStorageSync('token'),
                'partner_id': wx.getStorageSync('partner_id'),
                'product_id': that.$data.goods.id
            }, (data) => {
            })
        }
    },
    gotoCart() {
        wx.switchTab({
            url: '/pages/mall/shopcart/index'
        })
    }
})